package com.voltmao.webpro.utils.wechat.core;

import com.voltmao.webpro.utils.http.HttpClientUtil;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * 用于调用凭证
 */
public class AccessToken {

    private static java.util.logging.Logger logger = java.util.logging.Logger.getLogger(AccessToken.class.getName());
    private Map<String, String> wxConfig;
    private Account account;

    private String access_token;       // 接口访问凭证
    private double expires_in;           // 凭证有效期，单位：秒

    public AccessToken(Account account, Map<String, String> wxConfig) {
        this.wxConfig = wxConfig;
        this.account = account;
    }

    /**
     * 得到微信授权 token
     *
     * @return
     */
    public String getAccessToken() {
        //判断是否有token和是否过期
        if (this.isValid()) {
            String sendUrl = wxConfig.get("wx.oauth2.accessToken")
                    .replace("APPID", account.getAppId())
                    .replace("SECRET", account.getAppKey());

            Map<String, Object> resultMap = HttpClientUtil.sendGetToMap(sendUrl, null);
            this.access_token = resultMap.get("access_token") + "";

            this.refreshExpires();
        }

        return access_token;
    }

    /**
     * 刷新失效时间
     */
    private void refreshExpires() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MINUTE, 1);
        this.expires_in = cal.getTime().getTime();
    }

    /**
     * 验证是否过期
     *
     * @return
     */
    public boolean isValid() {

        logger.info(" token isValid  ===> expires_in:" + this.expires_in + "    currentTm:" + System.currentTimeMillis());

        return this.expires_in < System.currentTimeMillis();
    }

//    public static void main(String[] args) {
////        AccessToken accessToken = new AccessToken();
//
//        System.out.println("access_token:"+accessToken.isValid());
//
//    }
}


